跳到主要内容

NC93 设计LRU缓存结构

https://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61

第一次解:

参考自: https://geektutu.com/post/geecache-day1.html

package main

import "container/list"

type Cache struct {
c map[int]*list.Element
ll *list.List
mem int
max int
}

type entry struct {
key int
value int
}

func (r *Cache) Get(key int) int {
if ele, ok := r.c[key]; ok {
r.ll.MoveToFront(ele)
kv := ele.Value.(*entry)
return kv.value
}

return -1
}

func (r *Cache) RemoveOld() {
ele := r.ll.Back()
if ele != nil {
r.ll.Remove(ele)
kv := ele.Value.(*entry)
delete(r.c, kv.key)
r.mem--
}
}

func (r *Cache) Set(key, value int) {
if ele, ok := r.c[key]; ok {
r.ll.MoveToFront(ele)
kv := ele.Value.(*entry)
kv.value = value
} else {
ele := r.ll.PushFront(&entry{key, value})
r.c[key] = ele
r.mem++
}

if r.max != 0 && r.mem > r.max {
r.RemoveOld()
}
}

/**
* lru design
* @param operators int整型二维数组 the ops
* @param k int整型 the k
* @return int整型一维数组
*/
func LRU(operators [][]int, k int) []int {
var result []int
cache := &Cache{
c: make(map[int]*list.Element),
ll: list.New(),
mem: 0,
max: k,
}

for _, arr := range operators {
if arr[0] == 1 {
cache.Set(arr[1], arr[2])
} else if arr[0] == 2 {
result = append(result, cache.Get(arr[1]))
}
}

return result
}